#include "bsp_custom_data.h"
#include "string.h"
#include "esp_log.h"
static const char *TAG = "CUSTOM_DATA";

flash_ble_name_t flash_ble_name = {
    .flash_ble_name_flag = 0,
};


inline flash_ble_name_t *get_custom_data_flash_add()
{
    return &flash_ble_name;
}



/**
 * @brief               自定义数据读取
 * @param type          分区表 type属性
 * @param subtype       分区表 subtype属性
 * @param read_offset   读取的起始地址
 * @param dst           需要读取的内存指针
 * @param size          读取的长度
 * @return NULL
 */
void custom_data_read(uint8_t type, uint8_t subtype, size_t read_offset, void *dst, size_t size)
{
    esp_partition_t *find_partition = NULL;
    find_partition = esp_partition_find_first(type, subtype, NULL);
    if (find_partition == NULL){
        printf("find_partition_ERROR\n");
    }else{

        printf("find_partition\n");
    }
    
    esp_partition_read(find_partition, read_offset, dst, size);
}


/**
 * @brief               自定义数据写入
 * @param type          分区表 type属性
 * @param subtype       分区表 subtype属性
 * @param offset        写入的起始地址
 * @param src           需要写入的内存指针
 * @param size          写入的长度 (4k对齐)
 * @return NULL
 */
void custom_data_write(uint8_t type, uint8_t subtype, size_t offset, void *src, size_t size)
{
    esp_partition_t *find_partition = NULL;
    find_partition = esp_partition_find_first(type, subtype, NULL);
    esp_partition_erase_range(find_partition, offset, 0X1000);
    esp_partition_write(find_partition, offset, src, size);
}


void flash_ble_info_init()
{
    custom_data_read(FLASH_BLE_DATA_TYPE, FLASH_BLE_DATA_SUBTYPE, FLASH_BLE_DATA_OFFSET, &flash_ble_name, sizeof(flash_ble_name_t));
}


/**
 * @brief                   ble蓝牙数据更新
 * @param ble_name_str      需要更新的ble蓝牙名称
 * @return NULL
 */
void Ble_info_data_updata(uint8_t *ble_name_str)
{
    flash_ble_name.flash_ble_name_flag = BLE_NAME_SET_FLAG;
    memcpy(flash_ble_name.flash_ble_name, ble_name_str, sizeof(flash_ble_name.flash_ble_name));
    custom_data_write(FLASH_BLE_DATA_TYPE, FLASH_BLE_DATA_SUBTYPE, FLASH_BLE_DATA_OFFSET, &flash_ble_name, sizeof(flash_ble_name_t));
}

/**
 * @brief                   ble蓝牙数据内存读取
 * @return NULL
 */
void Ble_info_data_read()
{
    printf("读flash\n");
    custom_data_read(FLASH_BLE_DATA_TYPE, FLASH_BLE_DATA_SUBTYPE, FLASH_BLE_DATA_OFFSET, &flash_ble_name, sizeof(flash_ble_name_t));
}
















